package com.yupi.springbootinit.controller;

import com.yupi.springbootinit.annotation.OperationLog;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.processbatch.*;
import com.yupi.springbootinit.model.entity.BatchScheduleHistory;
import com.yupi.springbootinit.model.entity.ProcessBatch;
import com.yupi.springbootinit.model.entity.ProcessBatchStep;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.PMCTaskDetailVO;
import com.yupi.springbootinit.model.vo.pmc.PmcGroupedBatchesVO;
import com.yupi.springbootinit.model.vo.pmc.ProcessBatchDetailVO;
import com.yupi.springbootinit.model.vo.pmc.ProcessBatchProgressVO;
import com.yupi.springbootinit.service.ProcessBatchService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.service.WorkflowTaskService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * PMC相关接口
 */
@RestController
@RequestMapping("/pmc")
public class PmcController {

    @Resource
    private ProcessBatchService processBatchService;

    @Resource
    private UserService userService;

    @Resource
    private WorkflowTaskService workflowTaskService;

    /**
     * 生成版次
     */
    @PostMapping("/batches/generate")
    @OperationLog(operation = "新增", module = "PMC-版次")
    public BaseResponse<List<ProcessBatch>> generate(@RequestBody ProcessBatchAddRequest req, HttpServletRequest httpRequest) {
        if (req == null || req.getProcessSheetId() == null || req.getTotal() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "工艺单ID和版次数量不能为空");
        }

        User loginUser = userService.getLoginUser(httpRequest);
        List<ProcessBatch> list = processBatchService.generateBatches(
                req.getProcessSheetId(),
                req.getTotal(),
                req.getBatchCodes(),
                req.getBatchCodePrefix(),
                req.getBatchQuantities(),
                req.getDefaultQuantityPerBatch(),
                loginUser.getId(),
                loginUser.getUserName()
        );
        return ResultUtils.success(list);
    }

    /**
     * 认领PMC父任务
     */
    @PostMapping("/tasks/claim")
    @OperationLog(operation = "认领", module = "PMC-任务")
    public BaseResponse<Boolean> claimTask(@RequestBody PMCTaskClaimRequest req, HttpServletRequest httpRequest) {
        if (req == null || req.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        }
        User loginUser = userService.getLoginUser(httpRequest);
        boolean result = workflowTaskService.claimTask(req.getId(), loginUser.getId(), loginUser.getUserName(), loginUser.getDepartmentId());
        return ResultUtils.success(result);
    }

    @PostMapping("/batches/{id}/auto-schedule")
    @OperationLog(operation = "修改", module = "PMC-排程")
    public BaseResponse<ProcessBatch> autoSchedule(@PathVariable("id") Long id,
                                                   @RequestBody ProcessBatchScheduleAutoUpdateRequest req,
                                                   HttpServletRequest httpRequest) {
        if (id == null || id <= 0 || req == null || req.getPlanStart() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpRequest);
        return ResultUtils.success(
                processBatchService.autoSchedule(id, req.getPlanStart(), req.getStepDurations(), loginUser.getId(), loginUser.getUserName())
        );
    }

    @PutMapping("/batches/{id}/steps/duration")
    @OperationLog(operation = "修改", module = "PMC-排程")
    public BaseResponse<Boolean> updateStepDurations(@PathVariable("id") Long id,
                                                     @RequestBody ProcessBatchStepDurationUpdateRequest req,
                                                     HttpServletRequest httpRequest) {
        if (id == null || id <= 0 || req == null || req.getOverrides() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpRequest);
        boolean ok = processBatchService.updateStepDurations(
                id, req.getOverrides(), loginUser.getId(), loginUser.getUserName()
        );
        return ResultUtils.success(ok);
    }

    @PutMapping("/batches/{id}/schedule")
    @OperationLog(operation = "修改", module = "PMC-排程")
    public BaseResponse<Boolean> updateSchedule(@PathVariable("id") Long id,
                                                @RequestBody ProcessBatchScheduleUpdateRequest req,
                                                HttpServletRequest httpRequest) {
        if (id == null || id <= 0 || req == null || req.getPlanStart() == null || req.getReason() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpRequest);
        boolean ok = processBatchService.updateSchedule(id, req, loginUser.getId(), loginUser.getUserName());
        return ResultUtils.success(ok);
    }

    @PutMapping("/batches/{id}")
    @OperationLog(operation = "修改", module = "PMC-版次")
    public BaseResponse<Boolean> updateBatchBase(@PathVariable("id") Long id,
                                                 @RequestBody ProcessBatchUpdateRequest req,
                                                 HttpServletRequest httpRequest) {
        if (id == null || id <= 0 || req == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpRequest);
        boolean ok = processBatchService.updateBatchBase(id, req, loginUser.getId(), loginUser.getUserName());
        return ResultUtils.success(ok);
    }

    @PostMapping("/batches/{id}/submit")
    @OperationLog(operation = "发布", module = "PMC-版次")
    public BaseResponse<Boolean> submit(@PathVariable("id") Long id, HttpServletRequest httpRequest) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpRequest);
        boolean ok = processBatchService.submit(id, loginUser.getId(), loginUser.getUserName());
        return ResultUtils.success(ok);
    }

    @DeleteMapping("/batches/{id}")
    @OperationLog(operation = "删除", module = "PMC-版次")
    public BaseResponse<Boolean> deleteBatch(@PathVariable("id") Long id,
                                             @RequestBody ProcessBatchDeleteRequest req,
                                             HttpServletRequest httpRequest) {
        if (id == null || id <= 0 || req == null || req.getReason() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "版次ID和删除原因不能为空");
        }
        User loginUser = userService.getLoginUser(httpRequest);
        boolean ok = processBatchService.deleteBatch(id, req.getReason(), loginUser.getId(), loginUser.getUserName());
        return ResultUtils.success(ok);
    }

    /**
     * 获取批次列表
     * ✅ 修改：增加 taskId 参数，用于前端根据父任务ID查找子批次
     */
    @GetMapping("/batches")
    public BaseResponse<List<ProcessBatch>> listBatches(
            @RequestParam(required = false) Long taskId,
            @RequestParam(required = false) Long processSheetId,
            @RequestParam(required = false) String orderNumber,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) String status) {
        // Service 层需更新 listBatches 方法签名以接收 taskId
        return ResultUtils.success(processBatchService.listBatches(taskId, processSheetId, orderNumber, productName, status));
    }

    /**
     * 聚合列表
     */
    @GetMapping("/batches/grouped")
    public BaseResponse<List<PmcGroupedBatchesVO>> listBatchesGrouped(
            @RequestParam(required = false) Long processSheetId,
            @RequestParam(required = false) String orderNumber,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) String status) {
        return ResultUtils.success(processBatchService.listBatchesGrouped(processSheetId, orderNumber, productName, status));
    }

    @GetMapping("/batches/{id}")
    public BaseResponse<ProcessBatchDetailVO> getBatch(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(processBatchService.getBatchDetail(id));
    }

    @GetMapping("/batches/{id}/steps")
    public BaseResponse<List<ProcessBatchStep>> listSteps(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(processBatchService.listSteps(id));
    }

    @GetMapping("/batches/{id}/schedule-history")
    public BaseResponse<List<BatchScheduleHistory>> listScheduleHistory(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(processBatchService.listScheduleHistory(id));
    }

    @GetMapping("/tasks/{taskId}/detail")
    public BaseResponse<PMCTaskDetailVO> getPmcTaskDetail(@PathVariable("taskId") Long taskId, HttpServletRequest httpRequest) {
        if (taskId == null || taskId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpRequest);
        PMCTaskDetailVO detail = processBatchService.getPmcTaskDetail(taskId, loginUser.getId());
        return ResultUtils.success(detail);
    }

    @GetMapping("/batches/{id}/progress")
    public BaseResponse<ProcessBatchProgressVO> getBatchProgress(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "批次ID不能为空");
        }
        return ResultUtils.success(processBatchService.getBatchProgress(id));
    }

    /**
     * PMC批次排期
     */
    @PostMapping("/batches/schedule")
    @OperationLog(operation = "排期", module = "PMC-排程")
    public BaseResponse<ProcessBatch> scheduleBatch(
            @RequestBody BatchScheduleRequest req,
            HttpServletRequest httpRequest) {

        if (req == null || req.getBatchId() == null || req.getPlanStart() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "批次ID和计划开始时间不能为空");
        }

        User loginUser = userService.getLoginUser(httpRequest);

        ProcessBatch result = processBatchService.scheduleBatch(
                req.getBatchId(),
                req.getPlanStart(),
                req.getStepDurations(),
                loginUser.getId(),
                loginUser.getUserName()
        );

        return ResultUtils.success(result);
    }
}